import { useEffect } from 'react'
import Taro, { getEnv, ENV_TYPE } from '@tarojs/taro'

/**
 * 自定义摇一摇检测 Hook
 * @param threshold 触发阈值，默认 15
 * @param callback 触发后的回调
 */
export default function useShakeDetection(
  threshold = 15,
  callback: () => void
) {
  useEffect(() => {
    let lastTime = 0
    let lastX = 0, lastY = 0, lastZ = 0

    // 通用加速数据处理
    const handleData = (data: { x?: number; y?: number; z?: number }) => {
      const x = data.x || 0
      const y = data.y || 0
      const z = data.z || 0
      const now = Date.now()
      const diffTime = now - lastTime
      if (diffTime > 100) {
        const speed =
          Math.abs(x + y + z - lastX - lastY - lastZ) /
          diffTime *
          10000
        if (speed > threshold) {
          callback()
        }
        lastTime = now
        lastX = x
        lastY = y
        lastZ = z
      }
    }

    if (getEnv() === ENV_TYPE.WEAPP) {
      // 小程序平台：使用 Taro 加速度 API
      Taro.startAccelerometer({ interval: 'game' })
      const handleAcc = (res: any) => handleData(res)
      Taro.onAccelerometerChange(handleAcc)
      return () => {
        Taro.stopAccelerometer()
        Taro.offAccelerometerChange(handleAcc)
      }
    } else {
      // H5 平台：使用原生 devicemotion
      const handleMotion = (event: DeviceMotionEvent) => {
        if (!event.accelerationIncludingGravity) return
        handleData(event.accelerationIncludingGravity as any)
      }
      window.addEventListener('devicemotion', handleMotion)
      return () => {
        window.removeEventListener('devicemotion', handleMotion)
      }
    }
  }, [threshold, callback])
} 